<?php

class GFLimitByDay_Core
{
//    private static $settings;
    public function __construct()
    {
        if (!class_exists('GFCommon')) {
            add_action('admin_notices', array($this, 'dependencies_not_exists'));

            return;
        }
        add_action('init', array($this, 'add_languages_dir'));
//        $this->include_files();
        add_action('gform_editor_js', array($this, 'editor_script'));
        add_filter('gform_tooltips', array($this, 'add_gflimitbydayion_tooltips'));
        add_action('gform_field_standard_settings', array($this, 'gflimitbyday_standard_settings'), 10, 2);
        add_filter('gform_validation', array($this, 'gflimitbyday_validate'));
    }

    static function add_languages_dir()
    {
        load_plugin_textdomain('gflimitbyday',
            false,
            basename(dirname(GF_LIMIT_BY_DAY_INDEX_FILE)) . '/languages');
    }

    public function gflimitbyday_standard_settings($position, $form_id)
    {
        //create settings on position 25 (right after Field Label)
        if ($position == 25) {
            ?>
            <script>
                function gflimitbyday_activated(html_field, gform_field) {
                    //   console.log('arguments:', arguments);
                    const value = html_field.type.toString().toLowerCase() === 'checkbox' ? html_field.checked : Number(html_field.value);
                    SetFieldProperty(gform_field, value);
                    gflimitbyday_visibility();
                }

                function gflimitbyday_visibility() {
                    jQuery('#gflimitbyday_number_days_div').css({
                        'visibility': () => jQuery('#gflimitbyday_is_active')[0].checked === true ? 'visible' : 'hidden',
                        'height': () => jQuery('#gflimitbyday_is_active')[0].checked === true ? 'inherit' : '0px'
                    })

                }
            </script>
            <li class="gflimitbyday_setting field_setting ir_national_id_setting">
                <label for="gflimitbyday_is_active">
                    <?php esc_html_e('Set Limit for Days', 'gflimitbyday'); ?>
                    <?php gform_tooltip('form_field_gflimitbyday_value') ?>
                </label>
                <input type="checkbox" id="gflimitbyday_is_active"
                       onclick="gflimitbyday_activated(this,'gflimitbyday_is_active')"/>
                <?php esc_html_e('daily limit', 'gflimitbyday'); ?>
            </li>
            <li>
                <div id="gflimitbyday_number_days_div" style="visibility: hidden;display: flex">
                    <div>
                        <label for="field_admin_label">
                            <?php esc_html_e('days to wait', 'gflimitbyday'); ?>
                            <?php gform_tooltip('form_field_gflimitbyday_value') ?>
                        </label>


                        <input type="number" size="3" id="gflimitbyday_number_days" value="0"
                               onchange="gflimitbyday_activated(this,'gflimitbyday_number_days')"
                        />
                    </div>
                    <div style="width: 10%"></div>
                    <div>
                        <label for="gflimitbyday_number_unique">
                            <?php esc_html_e('number of uniques', 'gflimitbyday'); ?>
                            <?php gform_tooltip('form_field_gflimitbyday_value') ?>
                        </label>
                        <input type="number" size="3" id="gflimitbyday_number_unique" value="1"
                               onchange="gflimitbyday_activated(this,'gflimitbyday_number_unique')"
                        />
                    </div>

                </div>

            </li>


            <?php
        }
    }

    public function gflimitbyday_validate($validation_result)
    {
        //gflimitbyday_number_unique
        //gflimitbyday_number_days
        //gflimitbyday_is_active
//        self::err_log($validation_result);
        $formId = $validation_result['form']['id'];
        $fields = $validation_result['form']['fields'];

        foreach ($fields as $field) {
            if (!$field->gflimitbyday_is_active) continue;
            $gflimitbyday_number_days = intval($field->gflimitbyday_number_days);
            $gflimitbyday_number_unique = intval($field->gflimitbyday_number_unique);
            if ($gflimitbyday_number_days < 1 or $gflimitbyday_number_unique < 1) continue;
            $field_id = $field->id;
            $field_value = rgpost("input_$field_id");
            if ($field_value == null or $field_value == "") continue;
            $start_date = Date('Y-m-d', strtotime("-$gflimitbyday_number_days days"));
            $search_criteria = [];
            $search_criteria['status'] = 'active';
            $search_criteria['start_date'] = $start_date;
            $search_criteria['field_filters'][] = array('key' => $field_id, 'value' => $field_value);
            $count_entries = GFAPI::count_entries($formId, $search_criteria);
            if ($count_entries < $gflimitbyday_number_unique) continue;
            $sorting = array('key' => 'id', 'direction' => 'ASC');
            $paging = array('offset' => 0, 'page_size' => 1);
            $entry = GFAPI::get_entries($formId, $search_criteria, $sorting, $paging)[0];
            $dateInterval = date_diff(new DateTime(), new DateTime($entry['date_updated']));
            $days_to_wait = $gflimitbyday_number_days - $dateInterval->days;
            $validation_result['is_valid'] = false;
            $field->failed_validation = true;
            $field->validation_message = sprintf(__('%5$s %1$s is signed %2$s times in past %3$s days, please try %4$s days later',
                'gflimitbyday'),
                $field_value,
                $count_entries,
                $gflimitbyday_number_days,
                $days_to_wait,
                $field->label
            );

        }
        $validation_result['form']['fields'] = $fields;
        return $validation_result;
    }

    static function err_log($obj)
    {
        if (!WP_DEBUG) return;
        $log = print_r($obj, true);
        echo "
    <script>
    console.debug('$log');
</script>
    ";
        error_log($log);
    }

    public function editor_script()
    {
        ?>
        <script type='text/javascript'>
            //adding setting to fields of type "text"
            // console.log('fieldSettings', fieldSettings);
            fieldSettings.text += ', .gflimitbyday_setting';
            // if((typeof fieldSettings['ir_national_id']) !== 'undefined')
            // {
            fieldSettings.ir_national_id += ', .gflimitbyday_setting';
            // }

            //binding to the load field settings event to initialize the checkbox
            jQuery(document).on('gform_load_field_settings', function (event, field, form) {
                console.log('event, field, form', event, field, form);
                jQuery('#gflimitbyday_is_active').attr('checked', field['gflimitbyday_is_active']);
                if (typeof (field['gflimitbyday_number_unique']) !== 'undefined')
                    jQuery('#gflimitbyday_number_unique')[0].value = field['gflimitbyday_number_unique'];
                if (typeof (field['gflimitbyday_number_days']) !== 'undefined')
                    jQuery('#gflimitbyday_number_days')[0].value = field['gflimitbyday_number_days'];


                if (typeof (field['gflimitbyday_number_unique']) === 'undefined')
                    SetFieldProperty('gflimitbyday_number_unique', 1);
                if (typeof (field['gflimitbyday_is_active']) === 'undefined')
                    SetFieldProperty('gflimitbyday_is_active', 1);
                if (typeof (field['gflimitbyday_number_days']) === 'undefined')
                    SetFieldProperty('gflimitbyday_number_days', 0);
                gflimitbyday_visibility();

            });

        </script>
        <?php
    }

    public function add_gflimitbydayion_tooltips($tooltips)
    {
        $tooltips['form_field_gflimitbyday_value'] = sprintf('<h6>%1$s</h6><p>%2$s</p>    
                                                                     <h6>%3$s</h6><p>%4$s</p>
                                                                     <h6>%5$s</h6><p>%6$s</p>

                                                            
                                                            ', __('daily limit', 'gflimitbyday'),
            __('check this for making value unique for a period of days', 'gflimitbyday'),
            __('days to wait', 'gflimitbyday'),
            __('Number of days which user doesnt allow enter the value', 'gflimitbyday'),
            __('number of uniques', 'gflimitbyday'),
            __('how much times in period days user can enter the value default is 1 ', 'gflimitbyday'),


        );
        return $tooltips;
    }

    function dependencies_not_exists()
    {
        $message = sprintf(__('please install %1$s', 'gflimitbyday'), __('gravityforms', 'gflimitbyday'));
        $message = sprintf('<div class="notice notice-danger is-dismissible">
                                %1$s
                                <br>
                                 <a href="%2$s">
                                 %3$s
                                 </a>
                                 </div>
                ',
            esc_html($message),
            esc_html(__('https://gravityforms.com/', 'gflimitbyday')),
            esc_html(__('Get GravityForms', 'gflimitbyday')));
        printf($message);
        deactivate_plugins(plugin_basename(GF_LIMIT_BY_DAY_INDEX_FILE));
    }

    private function include_files()
    {
//        include 'class-text.php';
    }

}


new GFLimitByDay_Core();
